<?php
/**
 * Date: 2017/11/10
 * Time: 10:08
 * Author: zeronlee
 */

namespace App\Http\Controllers\Backend;


use App\Http\Controllers\Controller;
use App\Models\Ogz;
use App\Models\Access\User\User;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Http\Controllers\Traits\Base;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Traits\Users;

class OgzController extends Controller
{
    use Base;
    use Users;
    /**
     * {@inheritdoc}
     */
    protected function formatErrors(Validator $validator)
    {

        return $validator->errors()->all();
    }
    /**
     * 组织机构首页
     */
    public function index (){
        //机构列表
        $fields = ['o.id','o.name','o.pid'];
        //全局条件
        $ogzs = $this->getOgzs($fields,[0=>['o.deleted_at','==','NULL']]);
        $pageNum = 10;
        //联系人列表
        $users = $this->getUsers();
        $userLink = $this->userLinks();
        //需要启用权限
        $userLink['ogzs']['child'] = access()->hasOgzs(true);
        return view('backend.ogzindex')
            ->with('users',\GuzzleHttp\json_encode($users))
            ->with('ogzs',\GuzzleHttp\json_encode($ogzs))
            ->with('pageNum',$pageNum)
            ->with('links',\GuzzleHttp\json_encode($userLink));
    }
    /**
     * 组织机构首页
     */
    public function search (Request $request){
        $param = $request->input();
        //列表
        $fields = ['o.id','o.pid','o.name','o.description','o.sort','o.created_at','o.updated_at','u.id as user_id','u.name as user_name','o.deleted_at','o.user_id as many_user'];
        //多条件搜索
        $search = $param['search'];
        //默认值
        $search['value'] = empty($search['value']) ? '1&' : $search['value'];
        //搜索值按页面搜索框从左到右
        $filter = explode('&',$search['value']);
        //搜索
        $where = [];
        //展示tree
        $isTree = true;
        if ($filter[0]==1){

            $where[0] = ['o.deleted_at','==','NULL'];
        }
        if ($filter[0]==2){
            $isTree = false;
            $where[0] = ['o.deleted_at','!=','NULL'];
        }
        if (isset($filter[1]) && $filter[1]){
            $isTree = false;
            $where[1] = [['o.name','like','%'.$filter[1].'%'],['o.description','like','%'.$filter[1].'%']];
        }
        //记录数
        $count = Ogz::getList($fields,$where,true,$isTree);
        $ogzs = Ogz::getList($fields,$where,false,$isTree);
        $ogzObject = new Ogz();
        foreach ($ogzs as $ogz){

            $ogz->user_name = $this->getUserName($ogz->many_user);
            //是否拥有子级（非最低级）
            $ogz->hasChild = $ogzObject->hasChild($ogz->id);
        }
        $data = array('draw'=>$param['draw'],'recordsTotal'=>$count,'recordsFiltered'=>$count,'data'=>$ogzs);

        return response()->json($data);
    }

    /**
     * 全局数据验证
     */
    public function scopeValid ($data,$handleName='addOrUpdate'){
        $res = ['code'=>0];
        $userLinks = $this->userLinks();
        //需要启用权限
        $userLinks['ogzs']['child'] = access()->hasOgzs(true);
        if ($handleName == 'del') {
            if (in_array($data['id'], $userLinks['ogzs']['parent'])  || !in_array($data['id'],$userLinks['ogzs']['child'])) {
                $res['code'] = 403;
                $res['msg'] = '没有权限禁用或启用';
            }
        }
        else {
            if ($handleName == 'add') {
                //pid
                if (in_array($data['pid'], $userLinks['ogzs']['parent'])) {
                    $res['code'] = 403;
                    $res['msg'] = '没有权限添加该机构';
                }
            }
            if ($handleName == 'update') {
                //编辑需要当前机构id
                if (isset($data['id'])) {
                    //id
                    if (in_array($data['id'], $userLinks['ogzs']['parent'])  || !in_array($data['id'],$userLinks['ogzs']['child'])) {
                        $res['code'] = 403;
                        $res['msg'] = '没有权限编辑该记录';
                    }
                    //pid
                    $row = Ogz::find($data['id']);
                    //如果当前pid在未授权列表，只可以编辑当前
                    unset($userLinks['ogzs']['parent'][array_search($row->pid,$userLinks['ogzs']['parent'],true)]);
                    array_push($userLinks['ogzs']['child'], $row->pid);
                    if (in_array($data['pid'], $userLinks['ogzs']['parent']) || (!in_array($data['pid'],$userLinks['ogzs']['child']) && $data['pid'] != 0)) {
                        $res['code'] = 403;
                        $res['msg'] = '没有权限选择该父机构';
                    }
                }
            }
            //user_id
            $users = $this->getUsers();
            $go = false;
            foreach ($users as $user){
                if (empty($data['contact']) || $user->id == $data['contact']){
                    $go = true;
                }
            }
            if (!$go){
                $res['code'] = 403;
                $res['msg'] = '没有权限选择该用户';
            }
        }
        return $res;
    }

    /**
     * 数据验证
     */
    public function validateForm ($request,$type='add') {

        $this->validate($request, [
            'pid' => 'required|integer',
            'name' => ['required',Rule::unique('ogz')->ignore($request->id)],
            'description' => 'required',
            // 'user_id' => 'required'
        ], [
            'pid.required' => '请选择父机构',
            'name.required' => '请填写名称',
            'name.unique' => '该名称已存在',
            'description.required' => '请填写描述',
            // 'user_id.required' => '请选择联系人'
        ]);
    }

    /**
     * 添加机构
     */
    public function add (Request $request){
        $res['code'] = 0;
        $this->validateForm($request);

        $data = $request->input();
        //全局验证
        $valider = $this->scopeValid($data,'add');
        if ($valider['code']!==0){
            $res['code'] = $valider['code'];
            $res['msg'] = $valider['msg'];
        }else{
            //如何自定义错误json返回
            $data['user_id'] = isset($param['user_id']) ? implode(',',$param['user_id']):'';
            $data['sort'] = 0;
            unset($data['id']);
            if (!Ogz::insertRow($data)){
                $res['code'] = 500;
                $res['msg'] = '添加失败';
            }
        }
        return response()->json($res);
    }
    /**
     * 修改机构
     */
    public function update (Request $request){
        $data['code'] = 0;
        $this->validateForm($request,'update');
        $param = $request->input();
        //全局验证
        $valider = $this->scopeValid($request->input(),'update');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg'] = $valider['msg'];
        }else{
            $param['user_id'] = isset($param['user_id']) ? implode(',',$param['user_id']):'';
            $param['updated_at'] = Carbon::now();
            if(!Ogz::updateRow(array('id',$param['id']),$param)){
                $data['code'] = 500;
                $data['msg'] = '修改失败';
            }
        }
        return response()->json($data);
    }
    /**
     * 删除机构
     */
    public function delete (Request $request){
        $ogz = new Ogz();

        $data['code'] = 0;
        //全局验证
        $valider = $this->scopeValid($request->input(),'del');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg'] = $valider['msg'];
        }else{

            try{
                $ogz->deleteRow($request);

            }catch (\Exception $e){
                $data['code'] = 403;//非法操作

                $data['msg'] = $e->getMessage();

            }
        }
        return response()->json($data);

    }
    /**
     * 激活
     */
    public function active (Request $request){
        $data['code'] = 0;
        //软删除
        $valider = $this->scopeValid($request->input(),'del');
        if ($valider['code']!==0){
            $data['code'] = $valider['code'];
            $data['msg'] = $valider['msg'];
        }else{
            $ogz = new Ogz();
            if (!$ogz->activeRow($request)){
                $data['code'] = 500;
                $data['msg'] = '服务器忙';
            }
        }
        return response()->json($data);
    }
}